<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\model\EntityModel;
use common\model\ProjectModel;
use common\model\TaskModel;
use common\model\UserModel;
use teamones\Request;

class BatchCreateEntityChat extends BaseConsumer
{
    // 要消费的队列名
    public $queue = 'batch_create_entity_chat';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    public function doConsume($data)
    {
        $type = $data['type'] ?? 'design';
        $entityList = [];
        $relateChatEntityIds = [];
        $entityData = [];
        try {
            if ($type == 'design') {
                $entityData = $data['entity_ids'];
                $relateChatEntityIds = $data['entity_ids'];
            } else if ($type == 'storyboard') {
                $entityData = $data['entity'];
                $relateChatEntityIds = array_column($data['entity'], 'id');
            }
            $requestData = [
                "param" => [
                    "filter" => [
                        "link_id" => ['-in', implode(',', $relateChatEntityIds)],
                        'link_type' => 'entity',
                    ],
                ],
            ];
            $entityChatList = teamones_request('teamones-im', 'chat/select', $requestData);
            // 获取已有的实体任务群
            $entityChatMap = array_column($entityChatList['data']['rows'], null, 'link_id');
            foreach ($entityData as $entityItem) {
                $tmpChat = '';
                if ($type == 'design') {
                    // 如果有了就保存群聊ID
                    if (array_key_exists($entityItem, $entityChatMap)) {
                        $tmpChat = $entityChatMap[$entityItem]['global_id'];
                    }
                } else if ($type == 'storyboard') {
                    // 如果有了就保存群聊ID
                    if (array_key_exists($entityItem['id'], $entityChatMap)) {
                        $tmpChat = $entityChatMap[$entityItem['id']]['global_id'];
                    }
                }
                $entityList[] = ['chat_global_id' => $tmpChat, 'entity' => $entityItem];
            }
            foreach ($entityList as $entityItem) {
                $datum = $entityItem['entity'];
                $chatData = [];
                $receiver = [];
                $imUserIds = [];
                if ($type == 'design') {
                    $upstreamEntity = model(EntityModel::class)->where(['id' => $datum])->find();
                    // 获取对应项目下面的Code码实体
                    $downstreamEntity = model(EntityModel::class)
                        ->field('entity.*')
                        ->join('module m on m.id = entity.module_id')
                        ->where(["m.code" => ['IN', 'asset,level'], 'entity.code' => $upstreamEntity['code'], 'entity.project_id' => $upstreamEntity['project_id']])
                        ->find();
                    if ($downstreamEntity) {
                        $entityIds = [$downstreamEntity['id'], $datum];
                        // 获取任务的执行人和分配人
                        $entityTaskMember = model(TaskModel::class)
                            ->field('assignee,executor,assignee_producer')
                            ->where(['entity_id' => ['IN', $entityIds]])
                            ->group('assignee,executor,assignee_producer')
                            ->select();
                        $receiver = array_values(array_filter(array_unique(array_merge(array_merge($receiver, [$downstreamEntity['created_by']]), array_merge(array_column($entityTaskMember, 'assignee'), array_column($entityTaskMember, 'executor'), array_column($entityTaskMember, 'assignee_producer'))))));
                    }
                    $chatData = $upstreamEntity;
                } else if ($type == 'storyboard') {
                    $project = model(ProjectModel::class)->where(['id' => $datum['project_id']])->find();
                    $entityTaskMember = model(EntityModel::class)
                        ->field('t.assignee as assignee,t.executor as executor,t.assignee_producer as assignee_producer')
                        ->join('task t on t.entity_id = entity.id')
                        ->where(['entity.module_id' => module_by_code('shot')['id'], 'entity.initial_episode_code' => $datum['code'], 'entity.project_id' => $datum['project_id']])
                        ->group('t.assignee,t.executor,t.assignee_producer')
                        ->select();
                    $receiver = array_values(array_filter(array_unique(array_merge(array_merge($receiver, [$datum['created_by']]), array_merge(array_column($entityTaskMember, 'assignee'), array_column($entityTaskMember, 'executor'), array_column($entityTaskMember, 'assignee_producer'))))));
                    $datum['name'] = $project['name'] . '/' . $datum['name'];
                    $chatData = $datum;
                } else {
                    continue;
                }
                if ($receiver) {
                    $imUserIds = model(UserModel::class)->where(['id' => ['IN', $receiver]])->column('union_id');
                }
                if (empty($entityItem['chat_global_id'])) {
                    teamones_request('teamones-im', 'oauth/create_chat', ['data' => [
                        'chat' => [
                            'name' => $chatData['name'],
                            'type' => 'group',
                            'project_id' => $chatData['project_id'],
                            'link_id' => $chatData['id'],
                            'link_type' => 'entity',
                            'from_tenant_id' => $chatData['tenant_id'],
                            'created_by' => $chatData['created_by'],
                            'edited_at' => time()
                        ],
                        'chat_users' => $imUserIds,
                        'owner' => 0
                    ]]);
                } else {
                    teamones_request('teamones-im', 'oauth/invite_chat_user', ['data' => [
                        'chat_global_id' => $entityItem['chat_global_id'],
                        'user_id' => $imUserIds,
                    ]]);
                }
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
